package ChatNI;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import Controller.User;
import Signals.AbstractMessage;
import Signals.TextMessage;
import Signals.typeContenu;

public class UDPServer extends Thread {
	/* TODO UTILISER UN MEME SOCKET POUR SERVER ET SENDER ? */
	private DatagramSocket serverSocket;
	private byte[] receiveData;
	private ChatNI ni;

	/**
	 * @param ni Network du ChatSystem
	 */
	public UDPServer(ChatNI ni) {
		this.ni = ni;
	}


	public void run()
	{
		try {
			receiveData = new byte[1024];
			// we create the socket on the given port
			serverSocket = new DatagramSocket(ChatNI.portudp);
			System.out.println("UDPServer : socket created");
			// we create an empty ObjectInputStream
			ObjectInputStream ois = null;
			System.out.println("UDPServer : listening");
			while(ni.isConnected())
			{
				try {
					DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
					//we collect the information of the receiving packet in our receivePacket
					serverSocket.receive(receivePacket);
					System.out.println("UDPServer : Packect received");
					// we collect the data of the packet in a ByteArrayInputStream
					ByteArrayInputStream bais = new ByteArrayInputStream(receiveData);
					ois = new ObjectInputStream(bais);
					//we collect the object present in the packet
					AbstractMessage o = (AbstractMessage) ois.readObject();

					//Due to the "type" of the object we treat it
					String sig = "";
					typeContenu signal = o.getTypeContenu();
					User u = new User(o.getNickname());
					switch (signal) {
					case HELLO:  sig = "Hello";
					if(!o.getNickname().contentEquals(ni.getLocalUser().getNameIP()))
						ni.processHello(u);
					break;
					case HELLOACK: sig = "HelloAck";
					ni.processHelloAck(u);
					break;
					case TEXTMESSAGE: sig = "TextMessage";
					TextMessage m =  (TextMessage)o;
					ni.processTextMessage(u, m.getMessage(), User.fromStringListToUserList(m.getListNicknamesDest()));
					break;
					case GOODBYE:  sig = "Goodbye";
					if(!o.getNickname().contentEquals(ni.getLocalUser().getNameIP()))
						ni.processGoodbye(u);
					break;
					}
					System.out.println(sig + "Received");

					InetAddress IPAddress = receivePacket.getAddress();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println("UDPServer : Could not find the class");
				}

			}
			serverSocket.close();
			this.interrupt();

		}catch (IOException e){
			e.printStackTrace();
		}
	}

}